# coding: utf-8
# 服务端
import pickle
import socket
import struct

import keyboard

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#关闭nagle算法
client.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, True)

#ip = ('172.16.49.129', 8082)  # 设置唯一的地址
#ip = ('localhost', 8082)  # 设置唯一的地址
ip = ('172.16.49.1', 8082)  # 设置唯一的地址
client.connect(ip)  # 绑定地址

dataBuffer = bytes()
headerSize = 4
sn = 0



def dataHandle(headPack, body):
    global sn
    sn += 1
    print("第%s个数据包" % sn)
    print("header:%d, bodySize:%s" % (headPack, len(body)))
    print(pickle.loads(body.decode("utf-8")))
    event = pickle.loads(body.decode("utf-8"))
    #方向键单独处理监控 up down事件
    directions = {'left': True, 'right': True, 'up': True, 'down': True}
    if directions[event.name]:
        if event.event_type == "up":
            keyboard.press(event)
        elif event.event_type == "down":
            keyboard.release(event.name)
    else:
        if event.event_type == "down":
            keyboard.press_and_release(event.name)

while True:
    # run=input('请输入命令：')      #用户交互界面
    # if not run:continue           #判断如果run为空就跳出
    # client.send(bytes(run,encoding='utf-8'))   #通过字节形式发送用户输入的的内容

    data = client.recv(1024)
    #the remote terminal is closed or no data is avialable; return ''
    if not data:
        print type(data)
        print data == ''
        break

    print("读取数据 buffer 1024 : %d" % len(data))
    if data:
        # 把数据存入缓冲区，类似于push数据
        dataBuffer += data
        while True:
            if len(dataBuffer) < headerSize:
                print("数据包（%s Byte）小于消息头部长度，跳出小循环" % len(dataBuffer))
                break

            # 读取包头
            # struct中:!代表Network order，3I代表3个unsigned int数据
            headPack = struct.unpack('i', dataBuffer[:headerSize])
            bodySize = headPack[0]

            # 分包情况处理，跳出函数继续接收数据
            if len(dataBuffer) < headerSize + bodySize:
                print("数据包（%s Byte）不完整（总共%s Byte），跳出小循环" % (len(dataBuffer), headerSize + bodySize))
                break
            # 读取消息正文的内容
            body = dataBuffer[headerSize:headerSize + bodySize]

            # 数据处理
            dataHandle(bodySize, body)

            # 粘包情况的处理
            dataBuffer = dataBuffer[headerSize + bodySize:]  # 获取下一个数据包，类似于把数据pop出

client.close()  # 关闭连接



# header = client.recv(4)  #fdfdfdfdfdfd 接收内容长度为4，并赋值给data
# print ("header %s %d", len(header), header)
# body_len = struct.unpack('i', header)[0]  # 解报头并索引出值赋值给head_len
# print "body_len %s" % body_len
# body_bytes = client.recv(body_len)  # 接收长度为head_len变量中的值，赋值给head_bytes
# print "body_bytes %s" % len(body_bytes)
# body_json = body_bytes.decode('utf-8')  # 把刚刚接收的内容进行转换，转换成utf-8
# print pickle.loads(body_json)
# keyboard.play(pickle.loads(body_json), speed_factor = -1)
